package com.ltmonitor.service;

import com.ltmonitor.util.StringUtil;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service("jt808ServerHandler")
public class JT808ServerHandler extends IoHandlerAdapter implements IJT808ServerHandler {
	private Logger logger = Logger.getLogger(JT808ServerHandler.class);


	public void exceptionCaught(IoSession session, Throwable e)
			throws Exception {
		this.logger.info(getSimNo(session) + "发生异常:" + e.getMessage());
	}

	private String getSimNo(IoSession session) {
		return "" + session.getAttribute("simNo");
	}


	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		//this.logger
				//.info("SimNo:" + session.getAttribute("simNo") + "发送成功!");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {

		String simNo = "" + session.getAttribute("simNo");
		session.closeNow();
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		IoSessionConfig cfg1 = session.getConfig();
		if (cfg1 instanceof SocketSessionConfig) {
			SocketSessionConfig cfg = (SocketSessionConfig) session.getConfig();
			// ((SocketSessionConfig) cfg).setReceiveBufferSize(4096);
			cfg.setReceiveBufferSize(2 * 1024 * 1024);
			cfg.setReadBufferSize(2 * 1024 * 1024);
			cfg.setKeepAlive(true);
			// if (session.== TransportType.SOCKET) {
			// ((SocketSessionConfig) cfg).setKeepAlive(true);
			((SocketSessionConfig) cfg).setSoLinger(0);
			((SocketSessionConfig) cfg).setTcpNoDelay(true);
			((SocketSessionConfig) cfg).setWriteTimeout(10000);
		}

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus idle)
			throws Exception {
		this.logger.error(getSimNo(session) + "连接空闲，将关闭");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
	}

}
